<?php

namespace app\portal\controller;

use app\admin\model\UserNotice;
use app\common\controller\PortalBase;
use think\Request;
use think\Config;

class Notice extends PortalBase {
  protected $model, $modelUserNotice;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->model = new \app\admin\model\Notice();
    $this->modelUserNotice = new UserNotice();
  }

  public function _initialize() {
    parent::_initialize();
  }

  public function index() {
    $rows = $this->model
      ->alias('n')
      ->join('__BASE_USER__ u', 'u.id=n.creator_uid', 'left')
      ->join('__USER_NOTICE__ un', 'un.nid=n.id AND un.uid=' . session('user_id'), 'left')
      ->field('n.*,u.realname,un.create_time as readtime')
      ->order('n.id DESC')
      ->paginate();

    if (request()->isAjax()) {
      $this->result($rows, 1);
    }

    return view('', ['rows' => $rows]);
  }

  public function view() {
    $id = input('id/d', 0, 'abs');
    $row = ($id > 0) ? $this->model->find($id) : NULL;
    if ($id > 0) {
      $row = $this->model
        ->alias('n')
        ->join('__BASE_USER__ u', 'u.id=n.creator_uid', 'left')
        ->join('__USER_NOTICE__ un', 'un.nid=n.id AND un.uid=' . session('user_id'), 'left')
        ->field('n.*,u.realname,un.create_time as readtime')
        ->find($id);
    }
    if (!$id || !$row) $this->error(lang('data empty'));

    if (request()->isAjax()) {
      $this->result($row, 1);
    }

    return view('', ['row' => $row]);
  }

  public function viewLayer() {
    $unReadIds = session('unReadIds');
    if ($unReadIds) {
      $id = $unReadIds[0];
    }
    $row = ($id > 0) ? $this->model->find($id) : NULL;
    if (!$row) $this->error(lang('data empty'));
    cmf_log('查看公告', $id, date('Y-m-d H:i'));

    return view('', ['row' => $row]);
  }

  /**
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\ModelNotFoundException
   * @throws \think\exception\DbException
   * 已读公告
   */
  public function read() {
    $id = input('id/d', 0, 'abs');
    $row = ($id > 0) ? $this->model->find($id) : NULL;
    if (!$row) $this->error(lang('data empty'));
    $data = [
      'nid' => $id,
      'uid' => $this->uid,
    ];
    try {
      $this->modelUserNotice->save($data);
    } catch (\Exception $e) {
      $this->error(lang('error') . $e->getMessage());
    }
    cmf_log('已读公告', $id, date('Y-m-d H:i'));
    $this->success(lang('success'));

  }

  public function unReadIds() {
    $model = new UserNotice();
    $unReadIds = $model->unReadIds();
    $this->result($unReadIds, 1);
  }

}